/**
 * @author klv
 */
var QS_sameStoreSales=function(){
    this.containerId = null;
    this.container = null;
    this.profile=null;
    this.id = null;
    this.el = null;
    this.html=null;
	this.datagrid = null;
	this.datagridWrapEl = null;
	this.dataGridColumn = [{
        header: 'Company',
        dataIndex: 'company',
        width: '20%',
		align: 'left'
    }, {
        header: 'Symbol',
        dataIndex: 'symbol',
        width: '15%',
		align: 'left'
    }, {
        header: 'Actual',
        dataIndex: 'actual',
		align: 'right',
        width: '15%',
		className:'bold-cell'
    }, {
        header: "Retail Metrics Consensus*",
        dataIndex: 'retail',
		align: 'right',
        width: '30%',
		className:'bold-cell'
    }, {
        header: "Price Reaction*",
        dataIndex: 'price',
		align: 'right',
        width: '20%',
		className:'bold-cell'
    }];
	this.serviceCode=QSPC.checkPermission(2.16)?'TRADERCAL':QSPC.checkPermission(2.15)?'INPLAYCAL':'';
};
QS_sameStoreSales.prototype = {
	init: function(containerId, profile, sId){
		this.containerId = containerId;
		this.container = $('#' + containerId);
		this.id = sId;
		this.profile = profile;
		this.html = '<div class="rtq-samestoresales"><div class="hd"></div><div class="bd"><div class="datagridWrap"><div class="rtq-no-info">No data available.</div></div></div></div>'
		this.el = $(this.html);
		this.el.appendTo(this.container);
		this.datagridWrapEl = this.el.find(".datagridWrap");
		this.timeEl = this.el.find('div.hd');
		this.datagrid = this._buildDataGrid(this.datagridWrapEl);
		this._bindUI();
	},
	_buildDataGrid: function(datagridwrap){
		var self = this;
		return new Util.DataGrid(datagridwrap, {}, {
			column: self.dataGridColumn,
			htmlLayer: 'div',
			autoWidth: true,
			indexColKey: 'rowid',
			cellResize: true,
			cellRearrange: true,
			sortable: true,
            rowLayout: 'list',
			height: this.profile.height-60
		}, {
			onRowSelected: function(a, b){
				//self._onDatagridRowSelected(a, b);
			},
			onRowRemove: function(rowid){
				//self.removeRow(rowid);
			},
			onRowContextmenu: function(e, row){
				//                var date = row.data.pdate;
				//                watchlistContextMenu.Fun.WLdata.chartStartDate = watchlistContextMenu.Fun.exch(date);
				//                watchlistContextMenu.Fun.WLdata.securityType = gData[row.gkey] && gData[row.gkey]["mType"] ? gData[row.gkey]["mType"] : "ST"; // add the type of ticker to the right menu object.
				//                watchlistContextMenu.Fun.openContextMenu(e, row, self.wlObj, true);
			}
		});
	},
	_bindUI: function(){
		var self=this;
		//var rptDate = this._getDate();
		self.showLoading(true);
		DBHelper.getCalendar("6", null,this.serviceCode, function(data){
			if (data == null || data == '') {
				self.hideLoading();
				return;
			}
			data = $.evalJSON(data);
			if (!data["createDate"]) {
				data["createDate"] = "no time";
			}
			self.timeEl.empty();
			self.timeEl.append(self._createTimeHtml(data.createDate,false));
			self.datagrid.empty();
			self._bindData(data);
			self.hideLoading();
		});
	},
	_bindData:function(data){
		if (typeof data["sameStoreSales"] == 'undefined'||data["sameStoreSales"]==null) {
			this.datagridWrapEl.find(".rtq-no-info").show();
			return;
		}
		this.datagridWrapEl.find(".rtq-no-info").hide();
		var datatemp=data["sameStoreSales"];
		for(var i=datatemp.length-1;i>=0;i--){
			var d={
	            company: datatemp[i].company,
	            symbol: datatemp[i].ticker,
	            actual: datatemp[i].actual,
	            retail: datatemp[i].estimate,
	            price: datatemp[i].reaction,
	            rowid: i+1
	        };
			this.datagrid.addRow(d, i+1, 0);
			this._render(d);
		}
	},
	_render:function(d){
		if($.trim(d.actual)!="" &&!isNaN(d.actual)){
			this.datagrid.DOMMap[d.rowid]['actual'].style.color = parseFloat(d.actual) >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor;
		}
		if($.trim(d.retail)!="" &&!isNaN(d.retail)){
			this.datagrid.DOMMap[d.rowid]['retail'].style.color = parseFloat(d.retail) >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor;
		}
		if($.trim(d.price)!="" &&!isNaN(d.price)){
			this.datagrid.DOMMap[d.rowid]['price'].style.color = parseFloat(d.price) >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor;
		}
	},
    _createTimeHtml:function(date,isHideFont){
        isHideFont=isHideFont===true?true:false;
        if(isHideFont){
            return '<h3>'+date+'</h3>';
        }else{
            return '<h3>Updated: '+date+'</h3>';
        }
        
    },
    _addDate:function(y,m,d,n){
        var d = new Date(y,m-1,d);
        d.setDate(d.getDate()+n);
        return d;
    },
	_getDate:function(){
		date=new Date(),
        week=date.getDay(),
        year=date.getFullYear(),
        month=(date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1),
        day=date.getDate()<10?"0"+date.getDate():date.getDate();
		if(week==0){
            date=this._addDate(year,month,day,-2);
        }if(week==6){
            date=this._addDate(year,month,day,-1);
        }
		return this._formatDate(date,"yyyy-mm-dd");
	},
    _formatDate:function(date,type){
        var year=date.getFullYear(),
            month=(date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1),
            day=date.getDate()<10?"0"+date.getDate():date.getDate(),
            dateStr,
            monthCodes={"01":"Jan","02":"Feb","03":"Mar","04":"Apr","05":"May","06":"Jun",
            "07":"Jul","08":"Aug","09":"Sep","10":"Oct","11":"Nov","12":"Dec"};
        if(type=="yyyy-mm-dd"){
            dateStr=year+"-"+month+"-"+day;
        }
        if(type=="monthEng"){
            dateStr=monthCodes[month]+" "+day;
        }
        return dateStr;
    },
    changeOutSize:function(w,h){
        if(!h)  h=this.container.height()+20;
        this.datagrid.resize('auto', h-34);
    },
	fileMenuCallback:function(value){
		if(value!="refresh") return;
		this._bindUI();
	},
    saveConfig:function(){
        return {
        };      
    },
    clear:function(){
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }   
};
